import 'package:dio/dio.dart';
import '../../models/project_model.dart';
import '../../models/api_response.dart';

/// 项目API服务
class ProjectApiService {
  final Dio _dio;

  ProjectApiService(this._dio);

  /// 创建项目
  Future<ApiResponse<ProjectModel>> createProject(
      ProjectCreateRequest request) async {
    try {
      final response = await _dio.post('/projects', data: request.toJson());
      return ApiResponse.fromJson(
        response.data,
        (json) => ProjectModel.fromJson(json as Map<String, dynamic>),
      );
    } catch (e) {
      throw _handleError(e);
    }
  }

  /// 更新项目
  Future<ApiResponse<ProjectModel>> updateProject(
      int projectId, ProjectUpdateRequest request) async {
    try {
      final response =
          await _dio.put('/projects/$projectId', data: request.toJson());
      return ApiResponse.fromJson(
        response.data,
        (json) => ProjectModel.fromJson(json as Map<String, dynamic>),
      );
    } catch (e) {
      throw _handleError(e);
    }
  }

  /// 删除项目
  Future<ApiResponse<void>> deleteProject(int projectId) async {
    try {
      final response = await _dio.delete('/projects/$projectId');
      return ApiResponse.fromJson(response.data, null);
    } catch (e) {
      throw _handleError(e);
    }
  }

  /// 获取项目详情
  Future<ApiResponse<ProjectModel>> getProject(int projectId) async {
    try {
      final response = await _dio.get('/projects/$projectId');
      return ApiResponse.fromJson(
        response.data,
        (json) => ProjectModel.fromJson(json as Map<String, dynamic>),
      );
    } catch (e) {
      throw _handleError(e);
    }
  }

  /// 分页获取项目列表
  Future<ApiResponse<PageResponse<ProjectModel>>> getProjects({
    ProjectStatus? status,
    int? creatorId,
    String? keyword,
    int page = 0,
    int size = 10,
  }) async {
    try {
      final queryParams = <String, dynamic>{
        'page': page,
        'size': size,
      };

      if (status != null) queryParams['status'] = status.code;
      if (creatorId != null) queryParams['creatorId'] = creatorId;
      if (keyword != null && keyword.isNotEmpty) {
        queryParams['keyword'] = keyword;
      }

      final response =
          await _dio.get('/projects', queryParameters: queryParams);
      return ApiResponse.fromJson(
        response.data,
        (json) => PageResponse.fromJson(
          json as Map<String, dynamic>,
          (item) => ProjectModel.fromJson(item as Map<String, dynamic>),
        ),
      );
    } catch (e) {
      throw _handleError(e);
    }
  }

  /// 获取我的项目
  Future<ApiResponse<List<ProjectModel>>> getMyProjects() async {
    try {
      final response = await _dio.get('/projects/my');
      return ApiResponse.fromJson(
        response.data,
        (json) => (json as List<dynamic>)
            .map((item) => ProjectModel.fromJson(item as Map<String, dynamic>))
            .toList(),
      );
    } catch (e) {
      throw _handleError(e);
    }
  }

  /// 获取即将到期的项目
  Future<ApiResponse<List<ProjectModel>>> getProjectsNearDeadline() async {
    try {
      final response = await _dio.get('/projects/near-deadline');
      return ApiResponse.fromJson(
        response.data,
        (json) => (json as List<dynamic>)
            .map((item) => ProjectModel.fromJson(item as Map<String, dynamic>))
            .toList(),
      );
    } catch (e) {
      throw _handleError(e);
    }
  }

  /// 获取已过期的项目
  Future<ApiResponse<List<ProjectModel>>> getOverdueProjects() async {
    try {
      final response = await _dio.get('/projects/overdue');
      return ApiResponse.fromJson(
        response.data,
        (json) => (json as List<dynamic>)
            .map((item) => ProjectModel.fromJson(item as Map<String, dynamic>))
            .toList(),
      );
    } catch (e) {
      throw _handleError(e);
    }
  }

  /// 处理错误
  Exception _handleError(dynamic error) {
    if (error is DioException) {
      if (error.response != null) {
        final statusCode = error.response!.statusCode ?? 0;
        // 从响应体中提取错误消息
        String message = '请求失败';
        if (error.response!.data is Map<String, dynamic>) {
          final data = error.response!.data as Map<String, dynamic>;
          message = data['message'] ?? data['error'] ?? message;
        } else if (error.response!.data is String) {
          message = error.response!.data.toString();
        }
        
        // 根据状态码返回不同的异常类型
        if (statusCode == 401) {
          return const BusinessException(
            message: '认证失败，请重新登录',
            code: 401,
          );
        } else if (statusCode == 403) {
          return const BusinessException(
            message: '权限不足，无法执行此操作',
            code: 403,
          );
        } else if (statusCode >= 500) {
          return BusinessException(
            message: '服务器内部错误，请稍后重试',
            code: statusCode,
          );
        }
        
        return NetworkException(
          message: message,
          statusCode: statusCode,
          originalError: error,
        );
      } else {
        return const NetworkException(message: '网络连接失败');
      }
    }
    return NetworkException(
      message: error.toString(),
      originalError: error,
    );
  }
}
